package com.ch.engine.daily.emptyFile;

import cn.hutool.core.io.FileUtil;
import com.ch.common.result.Result;
import com.google.common.collect.Lists;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 判断word和excel文件是否为空文件
 *
 * @author wangchunhui
 * @date 2025/3/24 17:23
 */
@RestController
@RequestMapping("/file/check")
public class WordFileCheckerController {

    public static final List<String> SUFFIX_EXCEL_XLS = Lists.newArrayList("xls", "XLS");
    public static final List<String> SUFFIX_EXCEL_XLSX = Lists.newArrayList("xlsx", "XLSX");

    public static final List<String> SUFFIX_WORD_DOC = Lists.newArrayList("doc", "DOC");
    public static final List<String> SUFFIX_WORD_DOCX = Lists.newArrayList("docx", "DOCX");

    /**
     * 判断文件是否为空文件
     *
     * @param file file
     * @return com.vims.common.core.result.Result
     * @author wangchunhui
     * @date 2025/3/17 16:28
     */
    @PostMapping("/test")
    public Result isFileEmpty(@RequestParam(value = "file") MultipartFile file) throws Exception {
        boolean isFileEmpty;
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        InputStream inputStream = file.getInputStream();
        if (SUFFIX_EXCEL_XLSX.contains(suffix)) {
            isFileEmpty = isExcelEmpty(new XSSFWorkbook(inputStream));
        } else if (SUFFIX_EXCEL_XLS.contains(suffix)) {
            isFileEmpty = isExcelEmpty(new HSSFWorkbook(inputStream));
        } else if (SUFFIX_WORD_DOCX.contains(suffix)) {
            isFileEmpty = isDocxEmpty(inputStream);
        } else if (SUFFIX_WORD_DOC.contains(suffix)) {
            isFileEmpty = isDocEmpty(inputStream);
        } else {
            throw new RuntimeException("未知文件类型，不予处理！");
        }
        return Result.SUCCESS(isFileEmpty);
    }

    /**
     * 处理 .docx 文件（Word 2007 及以上）
     *
     * @param fis fis
     * @return boolean
     * @author wangchunhui
     * @date 2025/3/24 18:29
     */
    private static boolean isDocxEmpty(InputStream fis) throws IOException {
        try (XWPFDocument document = new XWPFDocument(fis)) {
            return document.getParagraphs().isEmpty() && document.getTables().isEmpty();
        }
    }

    /**
     * 处理 .doc 文件（Word 97-2003）
     *
     * @param fis fis
     * @return boolean
     * @author wangchunhui
     * @date 2025/3/24 18:29
     */
    private static boolean isDocEmpty(InputStream fis) throws IOException {
        try (HWPFDocument document = new HWPFDocument(fis)) {
            Range range = document.getRange();
            return range.text().trim().isEmpty();
        }
    }


    public static boolean isExcelEmpty(Workbook workbook) {
        try {
            // 遍历每个 Sheet，检查是否有非空单元格
            for (Sheet sheet : workbook) {
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        if (cell.getCellType() != CellType.BLANK) {
                            return false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
